//
//  SocketManager.swift
//  cangchu
//
//  Created by kang on 2021/11/29.
//

import Foundation
import UIKit

public class SocketManager: SocketCallBack{
    
    public static let share = SocketManager()
    private var client:SocketClient!
    private var timer:Timer!
    private var callBack:SocketCallBack?
    
    private init(){
        client = SocketClient()
        client.callback = self
    }
    
    //MARK: -基础函数
    public func connect(url:String,callBack:SocketCallBack){
        WorkThreads.share.queue.async {
            self.callBack = callBack
            try? self.client.connect(url: url)
        }
    }
    
    public func reConnect(){
        if case SocketStatus.noConn = client.status{
            WorkThreads.share.queue.async {
                self.client?.socket?.connect()
            }
        }
    }
    
    public func disconnect(){
        if case SocketStatus.connSuccess = client.status{
            client.disconnect()
        }
    }
    
    public func send(message:Message,completion:@escaping (()->())){
        if case SocketStatus.connSuccess = self.client.status{
            send(content: message.getContent(), completion: completion)
        }else{
            Logger.log(message: "socket no connect")
        }
    }
    
    public func send(content:String,completion:@escaping (()->())){
        WorkThreads.share.queue.async {
            if case SocketStatus.connSuccess = self.client.status{
                self.client.send(content: content, completion: completion)
            }else{
                Logger.log(message: "socket no connect")
            }
        }
    }
    
    public func destory(){
        if timer != nil{
            timer.invalidate()
            timer = nil
        }
        client.destory()
        client = nil
    }
    
    //MARK: -连接回调处理
    public func connect(status: SocketStatus) {
        switch status{
        case .connSuccess:
            break
        case .connError(_, _):
            break
        case .noConn:
            break
        }
        
        callBack?.connect(status: status)
    }
    
    public func messsage(content: String) {
        callBack?.messsage(content: content)
    }
    
    public func reconnect(){
        WorkThreads.share.queue.async {
            self.client.reConnect()
        }
    }
    
    //MARK: -心跳
    public func sendHeartMessage(){
        if timer == nil{
            timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(repeatWorkItem), userInfo: nil, repeats: true)
        }
    }
    
    @objc private func repeatWorkItem(){
        WorkThreads.share.queue.async {
            let message = MessageFactory.createHearMessage(content: "")
            self.send(message: message,completion: {
                
            })
        }
    }
    
}
